<template>
  <Form ref="loginForm" :model="form" :rules="rules" @keydown.enter.native="handleSubmit">
    <FormItem prop="userName">
      <Input v-model="form.userName" type="text" placeholder="请输入用户名">
      <span slot="prepend">
          <Icon :size="16" type="ios-person"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem prop="password">
      <Input type="password" v-model="form.password" placeholder="请输入密码">
      <span slot="prepend">
          <Icon :size="14" type="md-lock"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem>
      <Button @click="handleSubmit" type="primary" long>登录</Button>
    </FormItem>
  </Form>
</template>

<script>
  import {url} from '../../../config/url'
  import { mapMutations } from 'vuex';
  export default {
    name: 'LoginForm',
    props: {
      userNameRules: {
        type: Array,
        default: () => {
          return [
            { required: true, message: '账号不能为空', trigger: 'blur' }
          ]
        }
      },
      passwordRules: {
        type: Array,
        default: () => {
          return [
            { required: true, message: '密码不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    data () {
      return {
        result:'',
        form: {
          userName: '',
          password: ''
        }
      }
    },
    computed: {
      rules () {
        return {
          userName: this.userNameRules,
          password: this.passwordRules
        }
      }
    },
    methods: {
      ...mapMutations(['changeLogin']),
      handleSubmit () {
        // this.$refs.loginForm.validate((valid) => {
        //   if (valid) {
        //     this.$emit('on-success-valid', {
        //       userName: this.form.userName,
        //       password: this.form.password,
        //     })
        //   }
        // });
        if(this.form.userName.length>0&&this.form.password.length>0){
          this.$axios.post(url+'/login',{
            'username':this.form.userName,
            'password':this.form.password
          },{
            headers:{
              'Content-Type':'application/json'
            }
          }).then(response => {
            if(response.data.error_code==0){
              this.userToken='Bearer '+response.data.data.token;
              this.changeLogin({Authorization:this.userToken});
              this.$router.push('/home')
            }
            else{
              alert("输入信息有误")
            }
            },(response=>{
              alert("服务器连接错误")
            })
          );
        }
        else{
          alert("登陆信息不全")
        }
      }
    }
  }
</script>

<style scoped>
</style>
